"""Property repository implementation (Synchronous)."""

from __future__ import annotations

from datetime import datetime
from typing import Any

from sqlalchemy import func, extract
from sqlalchemy.orm import Session

from ..models.property import Property
from ..models.enums import PropertyStatus, PropertyType
from .base import Repository
from ..schemas.property import PropertyCreate, PropertyUpdate


class PropertyRepository(Repository[Property, PropertyCreate, PropertyUpdate]):
    """Repository for Property operations (Synchronous)."""

    def __init__(self, session: Session) -> None:
        super().__init__(Property, session)

    def get_by_status(
        self, status: PropertyStatus, skip: int = 0, limit: int = 100
    ) -> list[Property]:
        """Get properties by status."""
        return (
            self.session.query(Property)
            .filter(Property.status == status)
            .order_by(Property.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_by_type(
        self, property_type: PropertyType, skip: int = 0, limit: int = 100
    ) -> list[Property]:
        """Get properties by type."""
        return (
            self.session.query(Property)
            .filter(Property.property_type == property_type)
            .order_by(Property.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def count_by_criteria(
        self,
        status: PropertyStatus | None = None,
        property_type: PropertyType | None = None,
    ) -> int:
        """Count properties by criteria."""
        query = self.session.query(func.count(Property.id))

        if status is not None:
            query = query.filter(Property.status == status)
        if property_type is not None:
            query = query.filter(Property.property_type == property_type)

        result = query.scalar()
        return int(result) if result is not None else 0

    def get_status_stats(self) -> dict[str, int]:
        """Get statistics by property status."""
        query = self.session.query(
            Property.status, func.count(Property.id).label("count")
        ).group_by(Property.status)

        return {status.value: count for status, count in query.all()}

    def get_type_stats(self) -> dict[str, int]:
        """Get statistics by property type."""
        query = self.session.query(
            Property.property_type, func.count(Property.id).label("count")
        ).group_by(Property.property_type)

        return {prop_type.value: count for prop_type, count in query.all()}

    def count_created_since(
        self,
        since: datetime,
    ) -> int:
        """Count properties created since a specific date."""
        query = self.session.query(func.count(Property.id)).filter(Property.created_at >= since)

        result = query.scalar()
        return int(result) if result is not None else 0

    def soft_delete(self, property_id: int, user_id: int) -> bool:
        """Soft delete a property (not implemented - properties table doesn't have is_deleted column)."""
        # Properties table doesn't have soft delete columns
        return False

    def get_available_properties(
        self, include_unavailable: bool = False, limit: int = 1000
    ) -> list[Property]:
        """
        获取可用房源列表 (用于智能匹配).

        Args:
            include_unavailable: 是否包含已租出房源
            limit: 最大返回数量

        Returns:
            list[Property]: 房源列表
        """
        query = self.session.query(Property).filter(Property.is_deleted == False)

        if not include_unavailable:
            query = query.filter(Property.status == PropertyStatus.VACANT)

        return query.order_by(Property.created_at.desc()).limit(limit).all()
